﻿Module sys_mwRegistry
  Const mwRegistryPath = "C:\yPara\mwRegistry\"


  Private Function fp(ByVal path As String, Optional ByVal fileName As String = "")
    fp = path + IIf(path.EndsWith("\"), "", "\") + fileName
  End Function
  Private Function appPath() As String
    Return fp(My.Computer.FileSystem.GetParentPath(Application.ExecutablePath))
  End Function

  Sub mwRegisterSelf()
    Dim exeName As String = IO.Path.GetFileNameWithoutExtension(Application.ExecutablePath)
    IO.Directory.CreateDirectory(mwRegistryPath)
    IO.File.WriteAllText(mwRegistryPath + exeName + ".mwreg", Application.ExecutablePath)
  End Sub

  Function ExePath(ByVal appName As String) As String
    On Error Resume Next
    Dim fileName As String = mwRegistryPath + appName + ".mwreg"
    If IO.File.Exists(fileName) Then Return IO.File.ReadAllText(fileName)
    If IO.File.Exists(appPath() + appName + ".exe") Then Return appPath() + appName + ".exe"
  End Function
  
  Sub startWebUpdate(ByVal appID As String, ByVal autoUpdate As Boolean)

    Dim updaterFilespec As String = ExePath("mwwebupdate")

    If updaterFilespec = "" OrElse My.Computer.FileSystem.FileExists(updaterFilespec) = False OrElse FileLen(updaterFilespec) < 40000 Then
      If Not autoUpdate Then MsgBox("Der Updater wurde nicht gefunden bzw. du hast eine veraltete Version. " + vbNewLine + "Wenn du die neuste Version hast, starte den Updater einmal von Hand und versuche es nochmals. Ansonsten melde dich bei Max Weller ;-)")
      Exit Sub
    End If

    Dim updaterPara(5) As String
    updaterPara(0) = appID 'appID
    updaterPara(1) = appPath() 'localFolder
    updaterPara(2) = "/autostart" 'autostart?
    updaterPara(3) = "/autoclose" 'autoclose?
    updaterPara(4) = Application.ExecutablePath 'startAfterUpdate(1)
    updaterPara(5) = "" 'startAfterUpdate(2)
    Dim updaterArguments As String = Join(updaterPara, "#²#")

    'MsgBox(updaterFilespec + " " + updaterArguments, , "Updater wird aufgerufen...")

    glob.saveParaFile()
    Process.Start(updaterFilespec, updaterArguments)

  End Sub

End Module
